import { defineStore } from "pinia";
import { reactive } from "vue";
import { loginApi, logout } from "@/api/user";
import router from "@/router";
export const useUserStore = defineStore(
  "user",
  () => {
    //定义管理用户数据的state
    const userInfo = reactive({
      name: "",
      principal: {},
      role: "",
      state: "",
      tenantId: "",
      userId: "",
    });
    // 定义获取接口数据的action函数
    const getUserInfo = async (formData: any) => {
      const res: any = await loginApi({ ...formData });
      if (res.code === 200) {
        router.replace("/");
        userInfo.name = res.value.name;
        userInfo.role = res.value.role;
        userInfo.principal = res.value.principal;
        userInfo.state = res.value.state;
        userInfo.tenantId = res.value.tenantId;
        userInfo.userId = res.value.userId;
      }
    };
    const logoutAct = async () => {
      const res: any = await logout();
        if (res['code'] === 200) {
          userInfo.name = "";
        userInfo.role = "";
        userInfo.principal = {};
        userInfo.state = "";
        userInfo.tenantId = "";
        userInfo.userId = "";
        router.replace('/login');
        }
    }
    // 以对象的形式把state和action return出去
    return { userInfo, getUserInfo, logoutAct };
  },
  {
    persist: true,
  }
);
